// we will get rip of all the try catch inside each of the middleware
// and collect all the throw here
const { isContractJson, getDebug } = require('./lib')
const debug = getDebug('errors-handler-middleware')
// @TODO NOT IN USE AT THE MOMEMENT

module.exports = function(config) {
  // return middleware
  return async function(ctx, next) {
    return next().catch(err => {
      // ctx.assert(err instanceof JsonqlServerError, 404 , 'Checking of this is what throw earlier');
      debug('Catch an error here', err)
      const { statusCode, message } = err;
      ctx.type = 'json';
      ctx.status = statusCode || 500;
      ctx.body = JSON.stringify({
        error: {
          className: 'JsonqlServerError',
          message
        }
      });
      ctx.app.emit('error', err, ctx)
    })
  }
}
